package snake;

import javax.swing.*;
import java.awt.*;
import java.util.LinkedList;

class GameView {
    private final Grid grid;
    private JPanel canvas;

    GameView(Grid grid){
        this.grid = grid;
    }

    public void init(){
        canvas = new JPanel(){
            @Override
            public void paintComponent(Graphics graphics){
                drawGridBackground(graphics);
                drawSnake(graphics, grid.getSnake());
                drawFood(graphics, grid.getFood());
                drawScore(graphics, grid.getScore(), grid.returnRecord());
            }
        };
    }

    public void draw(){
        canvas.repaint();
    }

    public JPanel getCanvas(){
        return canvas;
    }

    private void drawSnake(Graphics graphics,Snake snake){
        LinkedList<Node> body = snake.getBody();
        drawCircle(graphics, body.get(0), Color.YELLOW);
        int len = body.size();
        for(int i=1; i<len; i++){
            Node bodyPart = body.get(i);
            drawCircle(graphics, bodyPart, Color.BLUE);
        }
    }

    private void drawScore(Graphics graphics, int score, int record){
        graphics.setColor(Color.RED);
        graphics.drawString("Score:"+score+" History Highest:"+record,0,Settings.DEFUALT_NODE_SiZE);
    }

    private void drawFood(Graphics graphics, Node squareArea){
        drawCircle(graphics, squareArea, Color.GREEN);
    }

    private void drawGridBackground(Graphics graphics){
        //画白色边界
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0,0,Settings.DEFUALT_GRID_WIDTH*Settings.DEFUALT_NODE_SiZE,Settings.DEFUALT_NODE_SiZE);
        graphics.fillRect(0,0,Settings.DEFUALT_NODE_SiZE,Settings.DEFUALT_GRID_HEIGHT*Settings.DEFUALT_NODE_SiZE);
        graphics.fillRect(0,(Settings.DEFUALT_GRID_HEIGHT-1)*Settings.DEFUALT_NODE_SiZE,Settings.DEFUALT_GRID_WIDTH*Settings.DEFUALT_NODE_SiZE,Settings.DEFUALT_NODE_SiZE);
        graphics.fillRect((Settings.DEFUALT_GRID_WIDTH-1)*Settings.DEFUALT_NODE_SiZE,0,Settings.DEFUALT_NODE_SiZE,Settings.DEFUALT_GRID_HEIGHT*Settings.DEFUALT_NODE_SiZE);
        graphics.setColor(Color.BLACK);
        graphics.fillRect(Settings.DEFUALT_NODE_SiZE,Settings.DEFUALT_NODE_SiZE,(Settings.DEFUALT_GRID_WIDTH-2)*Settings.DEFUALT_NODE_SiZE,(Settings.DEFUALT_GRID_HEIGHT-2)*Settings.DEFUALT_NODE_SiZE);
    }


    private void drawCircle(Graphics graphics, Node squareArea, Color color){
        graphics.setColor(color);
        int size = Settings.DEFUALT_NODE_SiZE;
        graphics.fillOval(squareArea.getX()*size, squareArea.getY()*size, size, size);
    }

    public void showGameOverMessage() {
        JOptionPane.showMessageDialog(null, "游戏结束\n你的成绩为："+grid.getScore(), "游戏结束", JOptionPane.INFORMATION_MESSAGE);
    }
}
